﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;

using Meraz.Core.Repositories;
using Meraz.Core.Helpers;
using Meraz.Core.Model;
using System.Net;

namespace Meraz.Core.Commands
{
    public interface ICreateUrlRedirectCommand {
        IUrlRedirectRepository UrlRedirectRepository { get; set; }
        INetworkHelper NetworkHelper { get; set; }
        HttpStatusCode Status { get; set; }
        string Redirect { get; set; }
        void Execute(string url);
    }
    public class CreateUrlRedirectCommand : BaseCommand, ICreateUrlRedirectCommand
    {
        #region Properties
        [Inject]
        public IUrlRedirectRepository UrlRedirectRepository { get; set; }
        [Inject]
        public INetworkHelper NetworkHelper { get; set; }
        public HttpStatusCode Status { get; set; }
        public string Redirect { get; set; }
        #endregion

        public void Execute(string url)
        {
            Status = HttpStatusCode.OK;
            Redirect = string.Empty;
            if (string.IsNullOrWhiteSpace(url))
                return;

            string finish = null;
            UrlRedirect redirect = UrlRedirectRepository.GetByUrl(url);
            if (redirect == null)
            {
                try
                {
                    Status = NetworkHelper.GetRedirect(url, out finish);
                }
                catch
                {
                    //sink error
                    Status = HttpStatusCode.BadRequest; //when error is unknown
                }
                if (!string.IsNullOrWhiteSpace(finish))
                {
                    redirect = new UrlRedirect();
                    UrlRedirectRepository.Add(redirect);
                    redirect.Start = url;
                    redirect.Finish = finish;
                    Commit();
                    Redirect = finish;
                }
            }
            else
                Redirect = redirect.Finish;
        }
    }
}
